import 'dart:convert';

import 'package:drm/base/login_result_entity.dart';
import 'package:drm/http/dioUtil.dart';
import 'package:drm/http/http_url.dart';
import 'package:drm/util/SpUtils.dart';
import 'package:equatable/equatable.dart';

import '../base/user.dart';
import '../util/SpUtils.dart';




abstract class LoginEvent extends Equatable {
  LoginEvent([List props = const []]) : super(props);
}


class NullLoginEvent extends LoginEvent {

}
// 获取user本地用户；
class LoadLoaclUser extends LoginEvent {

  User user ;
  LoadLoaclUser() : super();
  getLocalUser() {
    try {
      this.user = SpUtils.getLocalUser() ;
    }catch(e) {
      print(e.toString());
    }

  }
}

//登录；
class Login extends LoginEvent {
  User user;

  Login(this.user) : super([user]);
  Future<LoginResultEntity> login() async {
    LoginResultEntity loginResultEntity ;

      Result result = await DioUtil.post(AppUrl.getLoginUrl(), data:this.user.toJson()) ;
      if (result.isSuccess) {
        try {
          loginResultEntity = LoginResultEntity.fromJson(jsonDecode(result.data)) ;
          if (loginResultEntity.info == '登陆成功') {
            loginResultEntity.isSuccess = true;
          }else {
            loginResultEntity.isSuccess = false;
          }
        }catch(e) {
          loginResultEntity = LoginResultEntity(isSuccess: false,info: '请求成功返回数据错误');
        }
      }else {
        loginResultEntity = LoginResultEntity(isSuccess: false,info: '请求错误，请检查服务器是否配置正确');
      }



     return  loginResultEntity ;
  }
}

/*
    点击是否显示密码

 */
class LoginPassWordEditEvent extends LoginEvent {
    bool isObscure ;
    LoginPassWordEditEvent(this.isObscure):super([isObscure]);
}


/*
 * 当用户名改变时，密码自动清空；
 */
class LoginUserNameEditChanagedEvent extends LoginEvent {
  LoginUserNameEditChanagedEvent() : super();
}


/*
 *
 *  登录的数据校验；
 */
class LoginCheckEvent extends LoginEvent {
  User user ;
  String nameError;
  String passwordError;
  LoginCheckEvent(this.user, this.nameError, this.passwordError):super([user,nameError,passwordError]);


  bool check() {
    nameError = null ;
    passwordError = null ;
     if (user.loginName.trim().isEmpty) {
       nameError = '用户名不能为空';
       return false;
     }

     if (user.password.trim().isEmpty) {
       passwordError = '密码不能为空';
       return false;
     }

     return true;
  }


}

/*
 * 是否保存密码的checkBox，点击，改变的事件；
 */
class LoginSaveUserChangedEvent extends LoginEvent {
  bool isSaveUser = false;

  LoginSaveUserChangedEvent(this.isSaveUser):super([isSaveUser]);

}

/*
 * 网络请求登录成功后，本地保存用户的json的String数据；
 */
class LoginSaveUserEvent extends LoginEvent {
  User user;

  LoginSaveUserEvent(this.user):super([user]);

  Future<bool> saveUser() async {
    bool result = await SpUtils.saveLocalUser(user);
    return result;
  }


}




